<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class Transaction {

    /**
     * 
     * @global type $database
     * @return type
     */
    public function getContractes() {
        global $database;

        $result = $database->database_query(" 
            SELECT * FROM transaction_parameter WHERE contract_code NOT IN 
                (SELECT contract_code FROM transaction)
            ");
        $arr = array();
        while ($row = $database->database_fetch_assoc($result)) {
            $arr[] = $row;
        }
        return $arr;
    }

    /**
     * 
     * @global type $database
     * @param type $code
     * @return type
     */
    public function getContract($code = null) {
        if (empty($code)) {
            return null;
        }
        global $database;
        $result = $database->database_query(" SELECT * FROM transaction_parameter WHERE contract_code = '$code' LIMIT 1");
        return $database->database_fetch_assoc($result);
    }

    /**
     * 
     * @global type $database
     * @return type
     */
    public function getRepairUsers() {
        global $database;

        $result = $database->database_query("SELECT * FROM user WHERE type_id = 3");
        $users = array();
        while ($row = $database->database_fetch_assoc($result)) {
            $users[] = $row;
        }
        return $users;
    }

    /**
     * 
     * @global type $database
     * @return type
     */
    public function getKeyUsers() {
        global $database;

        $result = $database->database_query("SELECT * FROM user WHERE type_id = 2");
        $users = array();
        while ($row = $database->database_fetch_assoc($result)) {
            $users[] = $row;
        }
        return $users;
    }

    /**
     * 
     * @global type $database
     * @return type
     */
    public function getContents() {
        global $database;

        $result = $database->database_query(" SELECT * FROM content ");
        $content = array();
        while ($row = $database->database_fetch_assoc($result)) {
            $content[] = $row;
        }
        return $content;
    }
    /**
     * 
     * @global type $database
     * @param type $id
     * @return type
     */
    public function getTransactions($id = null){
        global $database;
        if(!empty($id)){
            $result = $database->database_query(" SELECT  p.* , t.* , c.name AS content_name, t.id AS transaction_id FROM transaction AS t
                LEFT JOIN content AS c ON t.content_id = c.id
                LEFT JOIN transaction_parameter AS p ON p.contract_code = t.contract_code
                WHERE t.id = $id LIMIT 1 ");
            return $database->database_fetch_assoc($result);
        }else{
            $result = $database->database_query(" SELECT * FROM transaction WHERE `status` <> 'deleted' ");
            $transactions = array();
            while ($row = $database->database_fetch_assoc($result)) {
                $transactions[] = $row;
            }
            return $transactions;
        }
    }
    /**
     * 
     * @global type $database
     * @param type $params
     * @return type
     */
    public function getList($params = array()){
        global $database, $user;
        $str = " SELECT  p.* , t.* , c.name AS content_name FROM transaction AS t
            LEFT JOIN content AS c ON t.content_id = c.id
            LEFT JOIN transaction_parameter AS p ON p.contract_code = t.contract_code 
            WHERE `status` <> 'deleted'
            ";
        
        if($user->user_info['type_id'] == 2){//key_partner_id
            $str .= " AND t.key_partner_id = {$user->user_info['id']} ";
        }elseif($user->user_info['type_id'] == 3){
            $str .= " AND t.room_partner_id = {$user->user_info['id']} ";
        }
//        if(!empty($params['contract_code'])){
//            $str .= " AND t.contract_code LIKE '%{$params['contract_code']}%' ";
//        }
//        if(!empty($params['status'])){
//            $str .= " AND t.status = '{$params['status']}' ";
//        }
        
        if(!empty($params)){
            foreach ($params as $key => $value) {
                if(!empty($value) && $key != 'offset' && $key != 'length'&& $key != 'page_number'){
                    if($key == 'contract_code' || $key == 'contract_cancel_date'){
                        if(strtolower(trim($value)) == 'blank'  ){
                            $str .= " AND ( t.$key IS NULL OR t.$key = '') ";
                        }else{
                            $str .= " AND t.$key LIKE '%$value%' ";
                        }
                    }else{
                        if(strtolower(trim($value)) == 'blank'  ){
                            $str .= " AND ( $key IS NULL OR $key = '') ";
                        }else{
                            $str .= " AND $key LIKE '%$value%' ";
                        }
                    }
                }
            }
            $str .= " ORDER BY t.id DESC ";
            if(!empty($params['offset']) || !empty($params['length'])){
                $str .= " LIMIT {$params['offset']} , {$params['length']} ";
            }
        }
        $result = $database->database_query($str);
        $transactions = array();
        while ($row = $database->database_fetch_assoc($result)) {
            $transactions[] = $row;
        }
        return $transactions;
        
    }
    /**
     * 
     * @global type $database
     * @param type $params
     * @return type
     */
    function getListItemsCount($params = array()) {
        global $database;
        $str = " SELECT  p.* , t.* , c.name AS content_name FROM transaction AS t
            LEFT JOIN content AS c ON t.content_id = c.id
            LEFT JOIN transaction_parameter AS p ON p.contract_code = t.contract_code 
            WHERE `status` <> 'deleted'
            ";
        if(!empty($params)){
            foreach ($params as $key => $value) {
                if(!empty($value) && $key != 'offset' && $key != 'length'&& $key != 'page_number'){
                    if($key == 'contract_code' || $key == 'contract_cancel_date'){
                        if(strtolower(trim($value)) == 'blank' ){ 
                            $str .= " AND ( t.$key IS NULL OR t.$key = '') ";
                        }else{
                            $str .= " AND t.$key LIKE '%$value%' ";
                        }
                    }else{
                        if(strtolower(trim($value)) == 'blank'  ){
                            $str .= " AND ( $key IS NULL OR $key = '') ";
                        }else{
                            $str .= " AND $key LIKE '%$value%' ";
                        }
                    }
                }
            }
        }
//        if(!empty($params['contract_code'])){
//            $str .= " AND t.contract_code LIKE '%{$params['contract_code']}%' ";
//        }
//        if(!empty($params['status'])){
//            $str .= " AND t.status = '{$params['status']}' ";
//        }
        $result = $database->database_query($str);
        return $database->database_num_rows($result);
    }
    /**
     * 
     * @global type $database
     * @param type $code
     * @param type $repair_id
     * @param type $content_id
     */
    public function createTransaction($code = null, $repair_id = 0, $content_id = 0) {
        if (empty($code) && empty($repair_id) && empty($content_id)) {
            return array(
                'status' => false,
                'error' => "Inputs are empty"
            );
        }
        global $database, $user;
        $date = date('Y-m-d H:i:s');
        $contract = $this->getContract($code);
        $deadline = '';
        $number = 0;
        if(!empty($contract)){
            $company_name = $contract['guarantee_company_name'];
            if(!empty($company_name)){
                $company = $database->database_fetch_assoc($database->database_query(" SELECT * FROM guarantee_company WHERE name = '$company_name' AND content_id = $content_id LIMIT 1"));
                if(!empty($company)){
                    $deadline = $company['info'];
                    $number = $company['payment_deadline'];
                }
            }
        }
        $database->database_query(" INSERT INTO transaction (
                                contract_code,
                                user_id,
                                content_id,
                                room_partner_id,
                                payment_day_number,
                                payment_deadline,
                                transaction_date_create,    
                                transaction_date_update
                              ) VALUES (
                                '{$code}',
                                '{$user->user_info['id']}',
                                '{$content_id}',
                                '{$repair_id}',
                                '{$number}',
                                '{$deadline}',
                                '{$date}',
                                '{$date}'
                              )
                            ");
        $id = $database->database_insert_id();
        if(!empty($id)){
            $mail_class = new Mail();
            $mail_class->sendMail('requestroomrepair', $id);
        }
        return $id;
    }

    /**
     * 
     * @global type $database
     * @global type $user
     * @param type $id
     * @param type $params
     * @return type
     */
    public function editTransaction($id = null, $params = array()){
        if(empty($id) || empty($params)){
            return array(
                'status' => false,
                'error' => "No update found!!"
            );
        }
        global $database, $user;
        $transaction = $this->getTransactions($id);
        
        $date = date('Y-m-d H:i:s');
        $query = "UPDATE transaction SET ";
        foreach ($params as $key => $value) {
            if(strpos($key, '_') === false && $key != 'payment' && $key != 'status'){
                continue;
            }
            if(!empty($value)){
                $query .= " `$key` = '$value' , ";
            }else{
                $query .= " `$key` = NULL , ";
            }
        }
        $query .= " `transaction_date_update` = '$date' WHERE id = {$id} ";
        $database->database_query($query);
        
        if($transaction){
            $mail = new Mail();
            if(isset($params['stop_renting_time']) && !empty($params['stop_renting_time']) && $params['stop_renting_time'] != 'blank' && strlen($params['stop_renting_time']) != 8){
                $params['stop_renting_time'] = $params['stop_renting_time'].':00';
            }
            if(isset($params['contract_cancel_date']) && $transaction['contract_cancel_date'] != $params['contract_cancel_date'] && !empty($params['contract_cancel_date']) && $params['contract_cancel_date'] != 'blank'){
                $mail->sendMail('datecontractcancel', $id);
            }
            if(isset($params['stop_renting_date']) && $transaction['stop_renting_date'] != $params['stop_renting_date'] && !empty($params['stop_renting_date']) && $params['stop_renting_date'] != 'blank'){
                $mail->sendMail('dateroomcancel', $id);
            }
            if(isset($params['stop_renting_time']) && $transaction['stop_renting_time'] != $params['stop_renting_time']&& !empty($params['stop_renting_time']) && $params['stop_renting_time'] != 'blank'){
                $mail->sendMail('datetimecancel', $id);
            }
            if(isset($params['way_to_see_room']) && $transaction['way_to_see_room'] != $params['way_to_see_room']){
                $mail->sendMail('donetoseeroom', $id);
            }
            if(isset($params['report_fee_text']) && $transaction['report_fee_text'] != $params['report_fee_text']){
                $mail->sendMail('reportfee', $id);
            }
            if(isset($params['accept_report_fee']) && $transaction['accept_report_fee'] != $params['accept_report_fee']){
                $mail->sendMail('acceptfee', $id);
            }
            if(isset($params['appointment_change_key_date']) && $transaction['appointment_change_key_date'] != $params['appointment_change_key_date']){
//                $mail->sendMail('acceptfee', $id);
                $mail->sendMail('requestchangekey', $id);
            }
            
            if(isset($params['funiture_repair']) && $transaction['funiture_repair'] != $params['funiture_repair']){
                $mail->sendMail('doneroomrepair', $id);
            }
            //
            if(isset($params['key_partner_id']) && !empty($params['key_partner_id']) && $transaction['key_partner_id'] != $params['key_partner_id']){
                $mail->sendMail('oldtrader', $id,$transaction['key_partner_id']);
            }
            if(isset($params['room_partner_id']) && !empty($params['room_partner_id']) && $transaction['room_partner_id'] != $params['room_partner_id']){
                $mail->sendMail('requestroomrepair', $id);
                $mail->sendMail('oldtrader', $id,$transaction['room_partner_id']);
            }
            if(isset($params['assign_key_date']) && $transaction['assign_key_date'] != $params['assign_key_date']){
                $mail->sendMail('assignedkey', $id);
            }
            if(isset($params['recovery_key_date']) && $transaction['recovery_key_date'] != $params['recovery_key_date']){
                $mail->sendMail('recoverykey', $id);
            }
            //last mail
            if(isset($params['contract_cancel_date']) && $transaction['contract_cancel_date'] != $params['contract_cancel_date'] && !empty($params['contract_cancel_date']) && $params['contract_cancel_date'] != 'blank'
                && isset($params['reception_date']) && $transaction['reception_date'] != $params['reception_date'] && !empty($params['reception_date']) && $params['reception_date'] != 'blank'
                    ){
                $mail->sendMail('canceldate', $id);
            }
            
        }
        return true;
    }
    
    public function deleteTransaction($id = null){
        global $database, $user;
        if(empty($id) || $user->user_info['type_id'] != 1){
            return array(
                'status' => false,
                'error' => "Cannot delete!!"
            );
        }
        $date = date('Y-m-d H:i:s');
        return $database->database_query(" UPDATE transaction SET  `status` = 'deleted' , `transaction_date_update` = '$date' WHERE id = {$id} ");
    }
    
    public function crontab(){
        global $database, $user;

        $mail = new Mail();
            if(isset($params['contract_cancel_date']) && $transaction['contract_cancel_date'] != $params['contract_cancel_date']){
                $mail->sendMail('datecontractcancel', $id);
            }
        $date = date('Y-m-d H:i:s'); 
        $result = $database->database_query(" SELECT  p.* , t.* , c.name AS content_name, t.id AS transaction_id FROM transaction AS t
            LEFT JOIN content AS c ON t.content_id = c.id
            LEFT JOIN transaction_parameter AS p ON p.contract_code = t.contract_code 
            WHERE t.id = 5
            ");
        //t.`status` = 'processing' AND 
        while ($row = $database->database_fetch_assoc($result)) {
            if(date('Y-m-d') == date("Y-m-d", strtotime($row['accept_report_fee'] . " +14 days")) && empty($row['funiture_repair'])){
                $mail->sendMail('remindfuniture14', $row['transaction_id']);
            }
            
            if (empty($row['payment']) && !empty($row['payment_day_number']) && !empty($row['contract_cancel_date'])){
                if(date('Y-m-d',  strtotime("{$row['contract_cancel_date']} + {$row['payment_day_number']} days")) == date("Y-m-d", strtotime("+7 days"))){
                    $mail->sendMail('deadlinepayment7', $row['transaction_id']);
                }
                if(date('Y-m-d',  strtotime("{$row['contract_cancel_date']} + {$row['payment_day_number']} days")) == date("Y-m-d", strtotime("+2 days"))){
                    $mail->sendMail('deadlinepayment2', $row['transaction_id']);
                }
            }
        }
    }
}
